#!/bin/bash

#variables
SERVICE='evince'
FILE=master.tex
PDFRUNNING=0
NOBIB="-o"
CHECK=$1

#Function for cleaning
function cleaning()
{
	rm master.aux
	rm master.log
	rm master.out
	rm master.synctex.gz
	rm master.toc
	rm master.bbl
	rm "master.synctex.gz(busy)"
	rm master.blg
	find . -name "*.aux" | xargs rm
 }

#Function for compiling
function compiling()
{
		pdflatex $FILE
		pdflatex $FILE
		if [[ "$CHECK" != "$NOBIB" ]]; then
			bibtex master.aux
			pdflatex $FILE
			pdflatex $FILE
		fi
		cleaning
}

#Check if certain service is running 
if ps ax | grep -v grep | grep $SERVICE > /dev/null
then
    PDFRUNNING=1
    killall -w $SERVICE

else
    PDFRUNNING=0
fi



if [[ -f master.aux ]]; then
	cleaning
fi

if [[ -f $FILE ]]; then
	compiling
else
	echo "$FILE does not exist, have you specified the correct location?"
	read -p "press Enter to quit"
	exit
fi



if [[ $PDFRUNNING == 1 ]]; then
	$SERVICE "master.pdf" &
fi